<template>
  <PageWrapper dense contentClass="flex">
    <DeptTree
      class="w-1/5 xl:w-1/6"
      @add="showModal"
      @select="selectCase"
      ref="caseTree"
    />
    <div class="ui-case-container">
      <!-- 容器显示，固定容器 -->

      <a-card title="用例步骤" style="height: 400px" class="container">
        <template #extra>
          <!-- <PlayCircleOutlined style="font-size: 25px" /> -->
          <a-button type="primary" v-if="(selectNode[0] || {}).type === 1" shape="circle" @click="runCase" :loading="loading">
            <template #icon>
              <PlayCircleOutlined />
            </template>
          </a-button>
          <a-button type="primary" v-if="(selectNode[0] || {}).type === 1" shape="circle" @click="saveCase">
            <template #icon>
              <SaveOutlined />
            </template>
          </a-button>
          <a-button type="primary" v-if="(selectNode[0] || {}).type === 1" shape="circle" @click="addStep">
            <template #icon>
              <PlusCircleOutlined />
            </template>
          </a-button>
          <!-- <PlusCircleOutlined style="font-size: 25px" @click="addStep" /> -->
        </template>
        <div class="steps_container">
          <draggable
          v-model="steps"
          group="steps"
          class="step-list"
          item-key="id"
          @start="onDragStart"
          @end="onDragEnd"
        >
          <template #item="{ element }">
            <StepComponent
              :step="element"
              v-model:step-description="element.step_description"
              v-model:assertion="element.assertion"
              :id="element.id"
              @delete="deleteStep"
              style="margin-bottom: 5px"
            />
          </template>
        </draggable>
        </div>
        <!-- 拖拽步骤组件 -->
        

        <!-- 添加步骤按钮 -->
        <!-- <button @click="addStep">添加步骤</button> -->

        <!-- 添加断言按钮 -->
      </a-card>
      <a-card title="录制结果" style="height: 400px">
        <video
          v-if="videoUrl"
          ref="videoPlayer"
          controls
          style="max-width: 100%; height: 300px; object-fit: contain"
        >
          <source   :src="videoUrl" type="video/webm" />
          您的浏览器不支持视频播放。
        </video>
        <p v-else>加载视频中...</p>

        <!-- 添加步骤按钮 -->
        <!-- <button @click="addStep">添加步骤</button> -->

        <!-- 添加断言按钮 -->
      </a-card>
    </div>

    <div
      id="log-container"
      style="
        height: 800px;
        width: 30%;
        overflow-y: scroll;
        background: #333;
        color: #aaa;
        margin-top: 24px;
        padding: 10px;
      "
    >
      <div><p v-for="(item, index) in logList">
          {{ item }}
      </p></div>
    </div>

    <a-modal
      v-model:open="open"
      title="Modal"
      ok-text="确认"
      cancel-text="取消"
      @ok="hideModal"
    >
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="名称"
          name="name"
          :rules="[{ required: true, message: 'Please input your name!' }]"
        >
          <a-input v-model:value="formState.name" />
        </a-form-item>

        <a-form-item label="类型">
          <a-radio-group v-model:value="formState.type">
            <a-radio value="0">模块</a-radio>
            <a-radio value="1">用例</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, unref, createVNode, reactive,watch } from "vue";
import { message } from "ant-design-vue";
import { v4 as uuidv4 } from "uuid";
import draggable from "vuedraggable";
import StepComponent from "./StepComponent.vue";
import { Modal } from "ant-design-vue";
import {
  PlusCircleOutlined,
  PlayCircleOutlined,
  ExclamationCircleOutlined,
  SaveOutlined,
} from "@ant-design/icons-vue";
import DeptTree from "./DeptTree.vue";
import { PageWrapper } from "@/components/Page";
import { createCase, debugCase, getCaseDebugLog,getCaseSteps,saveCaseSteps } from "@/views/uiauto/uiauto.api";

interface FormState {
  name: string;
  type: number;
  parent_id: string;
}

export default defineComponent({
  name: "UiCaseManage",
  components: {
    draggable,
    StepComponent,
    PageWrapper,
    DeptTree,
    PlusCircleOutlined,
    PlayCircleOutlined,
    ExclamationCircleOutlined,
    SaveOutlined,
  },
  setup() {
    const steps = ref([
      { id: uuidv4(), name: "步骤 1", step_description: "", assertion: "",order:1 },
    ]);

    const open = ref<boolean>(false);
    const caseTree = ref(null);
    let logList =ref([])

    // 定义收到的消息
    // const message = ref("");

    let intervalId: number | null = null;

    const selectNode = ref({});

    const loading = ref<boolean>(false);

    const formState = reactive<FormState>({
      name: "",
      type: 0,
      parent_id: "0",
    });

    const videoUrl = ref<string>(
      ""
    );
    const videoPlayer = ref(null);

    watch(videoUrl, (newValue, oldValue) => {
       refreshVideo()
    });

     // 刷新视频
     const refreshVideo=() =>{
      const video = videoPlayer.value;
      if (video){
      // 暂停当前视频
        video.pause();

      // 重置播放时间
        video.currentTime = 0;

      // 强制重新加载视频
        video.load();


      }
    };



    const getLogs = async ()=> {
      let data = unref(selectNode);
      let id = data[0].id
      intervalId=setInterval(async () => {
        try {
          const response = await getCaseDebugLog(id);
          console.log(response)
          if (response.task_status==0){
            clearTimeout(intervalId)
            loading.value=false
          }else{
            loading.value=true
          }
              // 替换为你的后端接口
          logList.value = response.data
            // 假设后端返回的内容是 { content: "文件内容" }
        } catch (error) {
          console.error("Error fetching file content:", error);
        }
      }, 2000)
    }; 

    //选中节点
    const selectCase = async (data) => {
      if(intervalId){
        clearTimeout(intervalId)
      }
      selectNode.value = data;
      videoUrl.value="http://192.168.0.56:8000/api/system/video?filename="+selectNode.value[0].id
      const result = await getCaseSteps(selectNode.value[0].id)
      if(result.steps.length>0){
          result.steps.sort((i1,i2)=>{
            return i1.order - i2.order
          })
      }
      steps.value=result.steps
      await getLogs()
     
      // sendTestMessage()
      // console.log(selectNode)
    };

    // 添加步骤
    const addStep = () => {
      steps.value.push({
        id: uuidv4(),
        name: `新步骤 ${steps.value.length + 1}`,
        step_description: "",
        assertion: "",
        order:steps.value.length + 1
      });
    };

    const deleteStep = (id)=>{
      const index = steps.value.findIndex((item) => item.id === id);

// 如果找到该项，则删除
    if (index !== -1) {
      steps.value.splice(index, 1);
      steps.value.forEach((item, index) => {
        item.order=index+1
      });
    } else {
      console.log(`未找到 ID 为 ${id} 的项`);
  }
    }

    const saveCase = async ()=>{
      if (steps.value.length ==0){
        message.info("请添加步骤")
        return 
      }
      const dataList = steps.value.map(item => ({ ...item ,case_id:selectNode.value[0].id}));
      // console.log(dataList)
      let data = await saveCaseSteps(selectNode.value[0].id,{steps:dataList,case_id:selectNode.value[0].id})
      message.success(data.data);
    }

    // 拖拽开始
    const onDragStart = () => {
      console.log("拖拽开始");
      
    };

    // 拖拽结束
    const onDragEnd = () => {
      console.log("拖拽结束");
      console.log(steps.value);
      
    };

    //运行用例
    const runCase = async () => {
      let data = unref(selectNode);

      const formattedData = [];

   
      steps.value.forEach((item) => {
        // 将每个用户的属性按照后端要求进行转换
        formattedData.push({
          id: item.id,
          stepDescription: item.step_description,
          assertion: item.assertion,
          caseId: data[0].id,
        });
      });
      let result = await debugCase(data[0].id, formattedData);
      message.warning(result.message);
      getLogs()
      
    };

    const showModal = (selectNode) => {
      if (selectNode === null) {
        message.warning("请先选中节点");
        return;
      }
      console.log(selectNode);
      // formState.parent_id = selectNode.id;
      formState.parent_id = selectNode[0].id;
      open.value = true;
      // console.log(formState)
    };

    const hideModal = async () => {
      let data = unref(formState);
      if (formState.parent_id === "0") {
        Reflect.deleteProperty(data, "parent_id");
      }
      
      await createCase(data);
      open.value = false;
      caseTree.value.fetch();
    };

    const confirm = () => {
      Modal.confirm({
        title: "Confirm",
        icon: createVNode(ExclamationCircleOutlined),
        content: "Bla bla ...",
        okText: "确认",
        cancelText: "取消",
      });
    };

  

 
    return {
      steps,
      open,
      videoUrl,
      loading,
      addStep,
      onDragStart,
      onDragEnd,
      showModal,
      hideModal,
      confirm,
      selectCase,
      runCase,
      saveCase,
      deleteStep,
      caseTree,
      selectNode,
      videoPlayer,
      formState,
      logList
    };
  },
});
</script>

<style scoped>
.ui-case-container {
  width: 60%;
  height: 100%;
  /* 设置容器高度为50% */
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin: 20px;
}



.container .steps_container{
  height: 320px;
  /* 使用100%来填充父容器 */
  overflow: auto;
}

.step-list,
.assertion-list {
  margin: 10px 0;
  min-height: 100px;
}

button {
  margin-top: 10px;
  padding: 5px 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style>
